<template>
  <view class="pageHeight wh_750 bg_F5F5F5 flex align-center flex-column">
    <s-header-title title="册谱背景"
                    is-fixed
                    background="#FFFFFF"
                    is-display-back
                    @getPageHeight="getPageHeight"
    ></s-header-title>
    <view :style="{height:`${page.pageHeight}px`}"></view>
    <view class="hW_38"></view>
    <view class="wh_690 listCover">
      <view class="wh_178 flex flex-column align-center"
            v-for="(item,index) in page.coverList"
            :key="index"
            @click.stop="selectCover(index)"
      >
        <view style="position: relative">
          <image class="wh_178 hW_253"
                 :src="item.url.indexOf('http') != -1 ? item.url : `${nc_image}${item.url}`"
                 style="box-shadow: 0rpx 3rpx 6rpx 1rpx rgba(0,0,0,0.16);border-radius: 8rpx"
          ></image>
          <image class="wh_62 hW_19 svip"
                 :src="`${IMG_URL}/index/vipopen.png`"
                 v-if="item.is_vip == 1"
          ></image>
          <view class="currentSelection flex align-center"
                v-if="page.currentIndex == index"
          >
            <image class="wh_20 hW_20"
                   :src="`${IMG_URL}/index/sq_select_icon_list.png`"
            ></image>
            <view class="ml_4">当前选择</view>
          </view>
        </view>
        <view class="mt_10">
          {{ item.title }}
        </view>
      </view>
    </view>
    <view class="hW_150"></view>
    <view class="bottomButton wh_470 hW_80 bg_FF4206 fs_30 fw_500 color_FFFFFF flex align-center justify-center"
          style="border-radius: 41rpx"
    >
      自定义封面
    </view>

    <s-popup-vip :show="vipDisposition.isShow" @closePopup="vipDisposition.isShow = false">
      <template #default>
        <view class="memberPopup position-relative"
              v-if="!!vipDisposition.goodDetails && vipDisposition.goodDetails != {}">
          <image class="w-100 h-100" :src="`${nc_image_path}/nc_vip_banner.png`"></image>
          <view class="exchange flex align-center justify-between">
            <view class="flex align-end" v-if="!!vipDisposition.goodDetails.price">
              <text>￥</text>
              <text class="fs_60" style="line-height: 60rpx">{{ vipDisposition.goodDetails.price[0] }}</text>
            </view>
            <view @click.stop="exchangeImmediately">
              兑换
            </view>
          </view>
          <view class="chatDetail fs_26 fw_500" style="color: #FDD07F"
                @click.stop="sheep.$router.go('/pages/public/richtext',{id:4,title:'会员权益'})"
          >
            查看详情
          </view>
          <view class="button_vip flex flex-row align-center justify-center" @click.stop="openImmediately">
            立即开通
          </view>
        </view>
      </template>
    </s-popup-vip>
  </view>
</template>

<script setup>
  import { reactive, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app';
  import sheep from '@/sheep';

  const page = reactive({
    options: {},
    pageHeight: 0,
    coverList: [],
    // 当前选择的封面下标
    currentIndex: 0,
  });
  const nc_image = computed(() => sheep.$store('AI').nc_image);
  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);
  const userInfo = computed(() => sheep.$store('user').userInfo);
  const nc_image_path = computed(() => sheep.$store('AI').nc_image_path);
  const vipDisposition = reactive({
    isShow: false,
    goodDetails: {},
  });

  onLoad(async (options) => {
    const { data } = await sheep.$api.goods.ids({ ids: '10' });
    vipDisposition.goodDetails = data[0];
    page.options = options;
    await getCoverList();
  });

  function getPageHeight(height) {
    page.pageHeight = height;
  }

  // 获取册谱封面列表
  async function getCoverList() {
    const { data } = await sheep.$api.book_list.getBookSysImageList({
      type: 2,
      genealogy_id: page.options.id,
    });
    page.coverList = data.sort((a, b) => a.id - b.id);
    page.coverList.forEach((item,index)=>{
      if(item.id == page.options.back_image){
        page.currentIndex = index;
      }
    })
  }

  function isVipExpired(userInfo) {
    return !userInfo.vip_end_time || new Date().getTime() / 1000 >= userInfo.vip_end_time;
  }

  async function updateBookCover(genealogyId, coverImageId) {
    try {
      const { code, msg } = await sheep.$api.book_list.updateBook({
        genealogy_id: genealogyId,
        back_image: coverImageId,
      });
      if (code == 1) {
        uni.$emit('getCanonizationDetail')
        return true;
      } else {
        sheep.$helper.toast(msg);
        return false;
      }
    } catch (error) {
      console.error('API call failed:', error);
      sheep.$helper.toast('网络请求失败，请稍后再试');
      return false;
    }
  }

  async function selectCover(index) {
    if(page.currentIndex == index){
      return
    }
    // 验证 index 是否有效
    if (index < 0 || index >= page.coverList.length) {
      console.error('Invalid index');
      return;
    }

    const cover = page.coverList[index];
    if (cover.is_vip == 1) {
      if (isVipExpired(userInfo.value)) {
        vipDisposition.isShow = true;
        return;
      }
    }

    if (await updateBookCover(page.options.id, cover.id)) {
      page.currentIndex = index;
    }
  }

  function exchangeImmediately() {
    sheep.$router.go('/pages/vip/memberCenter');
  }

  // 立即开通
  async function openImmediately() {
    let obj = {};
    let arr = [];
    arr.push({
      goods_id: vipDisposition.goodDetails.id,
      goods_num: 1,
      goods_sku_price_id: vipDisposition.goodDetails.id,
    });
    obj.goods_list = arr;
    obj.is_from = 1;
    obj.order_type = 'goods';
    const { code, data } = await sheep.$api.order.create(obj);
    uni.redirectTo({
      url: `/pages/pay/index?orderSN=${data.order_sn}&flag=1`,
    });
  }
</script>


<style scoped lang="scss">
  .listCover {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-column-gap: 55rpx;
    grid-row-gap: 20rpx;
    justify-items: center;
  }

  .currentSelection {
    position: absolute;
    left: 8rpx;
    bottom: 8rpx;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 18rpx;
    color: #4B4B4B;
  }

  .svip {
    position: absolute;
    right: 8rpx;
    top: 8rpx;
  }

  .bottomButton {
    position: fixed;
    left: 50%;
    transform: translateX(-50%);
    bottom: 50rpx
  }

  .memberPopup {
    width: 750rpx;
    height: 789rpx;

    .exchange {
      width: 325rpx;
      position: absolute;
      right: 215rpx;
      top: 154rpx;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 28rpx;
      color: #E94F09;
      padding: 0 0 5rpx 0;
    }
  }

  .button_vip {
    position: absolute;
    left: 50%;
    bottom: 110rpx;
    transform: translate(-50%, 0);
    width: 269rpx;
    height: 82rpx;
    background: url($uni-bg-url + '/nc_vip_button.png') no-repeat;
    background-size: 269rpx 82rpx;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 500;
    font-size: 41rpx;
    color: #FF4206;
  }

  .chatDetail {
    position: absolute;
    left: 50%;
    bottom: 270rpx;
    transform: translate(-50%, 0);
  }
</style>
